package service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import common.impl.exception.ServiceException;
import dao.interf.IAgentBaseConfigDAO;
import dao.interf.IAgentBaseDefDAO;
import dao.interf.IIfwAgentConsumeRecordDAO;
import dao.interf.IIfwAgentDevInfoDAO;
import dao.interf.IIfwAgentRegInfoDAO;
import dao.interf.IIfwCardInfoDAO;
import dao.interf.IIfwDeviceAuzInfoDAO;
import dao.interf.IIfwSrouterMapDAO;
import dao.pojo.AgentBaseConfig;
import dao.pojo.AgentBaseDef;
import dao.pojo.IfwAgentConsumeRecord;
import dao.pojo.IfwAgentDevInfo;
import dao.pojo.IfwAgentRegInfo;
import dao.pojo.IfwCardInfo;
import dao.pojo.IfwDeviceAuzInfo;
import dao.pojo.IfwSrouterMap;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import security.MySecurityContextHandle;
import service.interf.IIfwAgentConsumeRecord;

public class IfwAgentConsumeRecordImpl extends BaseDataServiceImpl implements IIfwAgentConsumeRecord {

	private IIfwAgentConsumeRecordDAO iIfwAgentConsumeDAO;
	private IIfwAgentRegInfoDAO iIfwAgentRegInfoDAO;
	private IIfwAgentDevInfoDAO iIfwAgentDevInfoDAO;
	private IIfwCardInfoDAO iIfwCardInfoDAO;
	private IfwCardInfo cardInfo;
	private IIfwDeviceAuzInfoDAO ifwDeviceAuzInfoDao;
	private IAgentBaseConfigDAO agentBaseConfigDao;
	private IAgentBaseDefDAO agentBaseDefDao;
	private IIfwSrouterMapDAO iIfwSrouterMapDao;

	public void setCardInfo(IfwCardInfo cardInfo) {
		this.cardInfo = cardInfo;
	}

	public void setiIfwCardInfoDAO(IIfwCardInfoDAO iIfwCardInfoDAO) {
		this.iIfwCardInfoDAO = iIfwCardInfoDAO;
	}

	public void setiIfwAgentRegInfoDAO(IIfwAgentRegInfoDAO iIfwAgentRegInfoDAO) {
		this.iIfwAgentRegInfoDAO = iIfwAgentRegInfoDAO;
	}

	public void setiIfwAgentDevInfoDAO(IIfwAgentDevInfoDAO iIfwAgentDevInfoDAO) {
		this.iIfwAgentDevInfoDAO = iIfwAgentDevInfoDAO;
	}

	public void setiIfwAgentConsumeDAO(IIfwAgentConsumeRecordDAO iIfwAgentConsumeDAO) {
		this.iIfwAgentConsumeDAO = iIfwAgentConsumeDAO;
	}

	public void setIfwDeviceAuzInfoDao(IIfwDeviceAuzInfoDAO ifwDeviceAuzInfoDao) {
		this.ifwDeviceAuzInfoDao = ifwDeviceAuzInfoDao;
	}

	public void setAgentBaseConfigDao(IAgentBaseConfigDAO agentBaseConfigDao) {
		this.agentBaseConfigDao = agentBaseConfigDao;
	}

	public void setAgentBaseDefDao(IAgentBaseDefDAO agentBaseDefDao) {
		this.agentBaseDefDao = agentBaseDefDao;
	}

	public void setiIfwSrouterMapDao(IIfwSrouterMapDAO iIfwSrouterMapDao) {
		this.iIfwSrouterMapDao = iIfwSrouterMapDao;
	}

	public String addConsume(IfwAgentConsumeRecord model) throws Exception {
		// 验证
		Integer agentIndex = MySecurityContextHandle.getAgentIndex();
		if (null == agentIndex)
			throw new ServiceException("请先登录");
		String userName = MySecurityContextHandle.getUserName();
		Integer times = model.getTime();
		if (null == times)
			throw new ServiceException("充值卡时长不能为空");
		// 验证主机数
		Integer host = model.getHost();
		if (null == host)
			throw new ServiceException("请输入主机数！");
//		if (host.intValue() > 600 || host.intValue() < 1)
//			throw new ServiceException("主机数必须大于0且小于等于600！");
		if (host.intValue() < 1)
			throw new ServiceException("主机数必须大于0！");
		int point = getPoint(userName, times, host);
		model.setType((short) 1);
		model.setTime(times);
		model.setPoint(point);
		model.setCtime(myDateHandle.getCurrentDTString());
		// 绑定代理商
		IfwAgentRegInfo agentRegInfo = iIfwAgentRegInfoDAO.findById(agentIndex);
		if (null == agentRegInfo)
			throw new ServiceException("代理商不存在");
		model.setIfwAgentRegInfo(agentRegInfo);

		// 绑定设备
		List<IfwAgentDevInfo> agentDevInfos = iIfwAgentDevInfoDAO.findByProperties(new String[] { "sn", "enabled" },
				new Object[] { model.getIfwAgentDevInfo().getSn(), true });
		if (null == agentDevInfos || agentDevInfos.isEmpty())
			throw new ServiceException("系统异常,请稍候再试!");

		IfwAgentDevInfo agentdevInfo = agentDevInfos.get(0);
		model.setIfwAgentDevInfo(agentdevInfo);
		model.setIfwCardInfo(null);
		model.setAc(0);
		// model.setHost(0);
		String result = "1";
		if (!"admin".equals(userName)) {
			// 扣除代理商响应点数
			Integer agentPoint = agentRegInfo.getAgentPoint();
			// 是否足够点数
			if (agentPoint - model.getPoint() < 0) {
				result = "2";
			} else {
				agentRegInfo.setAgentPoint(agentPoint - model.getPoint());
				iIfwAgentRegInfoDAO.update(agentRegInfo);
			}
		}
		if ("1".equals(result)) {
			// 修改设备到期时间
			List<IfwDeviceAuzInfo> list = ifwDeviceAuzInfoDao.findByProperties(new String[] { "sn" },
					new Object[] { agentdevInfo.getSn() });
			if (null == list || list.isEmpty())
				throw new ServiceException("未找到设备");
			IfwDeviceAuzInfo auz = list.get(0);
			String time = auz.getExpireTime();
			long ts;
			if (StringUtils.isEmpty(time)) {
				ts = new Date().getTime();
			} else {
				time = time.replaceAll("-", "");
				time = time.replaceAll(" ", "");
				time = time.replaceAll(":", "");
				time = time.substring(0, 14);
				ts = myDateHandle.MyStringToDateTime(time).getTime();
			}
			ts += 2678400000L * times;
			String time_new = myDateHandle.MyDateTimeToString(new Date(ts));
			time_new = myDateHandle.MyStringToISODateTimeString(time_new);
			auz.setExpireTime(time_new);
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String t = sf.format(new Date());
			auz.setRechargeLast(t);
			auz.setHost_allowed(model.getHost());
			auz.setAc_allowed(5);
			ifwDeviceAuzInfoDao.update(auz);
		}
		model.setResult(result);
		iIfwAgentConsumeDAO.save(model);
		return result;
	}

	public String addCard(IfwAgentConsumeRecord model) throws Exception {
		// 验证
		Integer agentIndex = MySecurityContextHandle.getAgentIndex();
		if (null == agentIndex)
			throw new ServiceException("请先登录");
		String userName = MySecurityContextHandle.getUserName();
		Integer times = model.getTime();
		if (null == times)
			throw new ServiceException("充值卡时长不能为空");

		// 验证主机数
		Integer host = model.getHost();
		if (null == host)
			throw new ServiceException("请输入主机数！");
//		if (host.intValue() > 600 || host.intValue() < 1)
//			throw new ServiceException("主机数必须大于0且小于等于600！");
		if (host.intValue() < 1)
		throw new ServiceException("主机数必须大于0！");

		int point = getPoint(userName, times, host);
		model.setType((short) 2);
		model.setTime(times);
		model.setPoint(point);
		model.setCtime(myDateHandle.getCurrentDTString());
		// 绑定代理商
		IfwAgentRegInfo agentRegInfo = iIfwAgentRegInfoDAO.findById(agentIndex);
		if (null == agentRegInfo)
			throw new ServiceException("代理商不存在");
		model.setIfwAgentRegInfo(agentRegInfo);

		// 购买结果
		String result = "1";
		String cardNum = "2";
		if (!"admin".equals(userName)) {
			Integer agentPoint = agentRegInfo.getAgentPoint();
			if (agentPoint == 0 || agentPoint < point) {
				result = "2";
				model.setIfwCardInfo(null);
			} else {
				// 扣除代理商响应点数
				agentRegInfo.setAgentPoint(agentPoint - point);
				iIfwAgentRegInfoDAO.update(agentRegInfo);
			}
		}
		model.setResult(result);
		model.setIfwAgentDevInfo(null);
		model.setAc(0);
		// model.setHost(0);
		iIfwAgentConsumeDAO.save(model);
		if (model.getResult().equals("1")) {
			// 创建及绑定卡号
			Long userId = MySecurityContextHandle.getUserId();
			String id = String.valueOf(userId);
			cardInfo = new IfwCardInfo();
			SimpleDateFormat num = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			cardNum = num.format(new Date());
			cardNum = id + cardNum;
			cardInfo.setCardNum(cardNum);
			cardInfo.setCardSta("valid");
			cardInfo.setTime(model.getTime());
			cardInfo.setTimeSec(model.getTime() * 2678400);
			cardInfo.setAc(5);
			cardInfo.setHost(model.getHost());
			iIfwCardInfoDAO.save(cardInfo);
			model.setIfwCardInfo(cardInfo);
			iIfwAgentConsumeDAO.update(model);
			return cardNum;
		} else {
			return "2";
		}
	}

	/**
	 * 获取当前代理商，充值指定时长需要的点数
	 * 
	 * @param userName
	 * @param times
	 * @return
	 * @throws Exception
	 */
	private int getPoint(String userName, Integer times, int host) throws Exception {
		int point = 0;
		// 获取当前代理商基数
		AgentBaseConfig agentBaseConfig = agentBaseConfigDao.findById(userName);
		Integer agentBase = null;
		if (null != agentBaseConfig) {
			agentBase = agentBaseConfig.getAgentBase();
		}
		if (null == agentBase || agentBase.intValue() < 1) {
			List<AgentBaseDef> agentBaseDefL = agentBaseDefDao.findAll(null);
			agentBase = agentBaseDefL.get(0).getAgentBase();
		}
		if (null == agentBase || agentBase.intValue() < 1) {
			agentBase = 600;
		}

		if (host >= 300) {
			int add = (int) Math.floor((host - 300) / 100);
			if (host % 100 >= 50)
				add += 1;
			// add = (int) Math.floor(agentBase / 3 * add);
			add = 240 * add;
			agentBase += add;
		}

		if (times.intValue() == 1) {
			point = (int) Math.floor(agentBase.doubleValue() / 12 * 1 * 1.5);
		} else if (times.intValue() == 3) {
			point = (int) Math.floor(agentBase.doubleValue() / 12 * 3 * 1.3);
		} else if (times.intValue() == 6) {
			point = (int) Math.floor(agentBase.doubleValue() / 12 * 6 * 1.1);
		} else if (times.intValue() == 12) {
			point = agentBase.intValue();
		} else if (times.intValue() == 24) {
			point = agentBase.intValue() * 2;
		} else {
			throw new ServiceException("参数错误!");
		}
		return point;
	}

	/**
	 * 代理商充值
	 */
	public String agentRecharge(Integer agentIndex, Integer point) throws Exception {
		// 验证admin
		String userName = MySecurityContextHandle.getUserName();
		if (!"admin".equals(userName))
			throw new ServiceException("充值失败，无该操作权限");
		IfwAgentRegInfo agentRegInfo = iIfwAgentRegInfoDAO.findById(agentIndex);
		if (null == agentRegInfo)
			throw new ServiceException("请选择代理商");
		if (null == point || point < 1 || point > 50000)
			throw new ServiceException("充值点数必须在1-50000之间");
		// 给代理商充值点数
		Integer agentPoint = agentRegInfo.getAgentPoint();
		if (null == agentPoint)
			agentPoint = 0;
		agentRegInfo.setAgentPoint(agentPoint + point);
		iIfwAgentRegInfoDAO.update(agentRegInfo);
		// 添加代理商充值记录
		IfwAgentConsumeRecord record = new IfwAgentConsumeRecord();
		record.setIfwAgentRegInfo(agentRegInfo);
		record.setPoint(point);
		record.setType((short) 3);
		record.setCtime(myDateHandle.getCurrentDTString());
		record.setResult("1");
		record.setAc(0);
		record.setHost(0);
		record.setTime(0);
		iIfwAgentConsumeDAO.save(record);
		return "1";
	}

	/**
	 * 阶段共计消费
	 */
	public String getTotal(Integer agentIndex, Short type, String startDate, String endDate) throws Exception {
		String userName = MySecurityContextHandle.getUserName();
		if (StringUtils.isEmpty(userName))
			throw new ServiceException("请先登录");
		String sql = "";
		int t = 0;
		if (null != type) {
			t = type.intValue();
		}
		if (null != agentIndex) {
			sql += "select sum(point) from ifw_agent_consume_record where result = 1 and agent_index = " + agentIndex;
			if (t == 1 || t == 2 || t == 3) {
				sql += " and type = " + t;
			} else {
				sql += " and type != 3";
			}
		} else {
			agentIndex = MySecurityContextHandle.getAgentIndex();
			sql += "select sum(point) from ifw_agent_consume_record where result = 1";
			if (t == 1 || t == 2) {
				sql += " and agent_index = " + agentIndex;
				sql += " and type = " + t;
			} else {
				if ("admin".equals(userName)) {
					if (t == 3) {
						sql += " and type = 3";
					} else {
						sql += " and (agent_index = " + agentIndex + " or type = 3)";
					}
				} else {
					if (t == 3) {
						sql += " and agent_index = " + agentIndex;
						sql += " and type = 3";
					} else {
						sql += " and agent_index = " + agentIndex;
						sql += " and type != 3";
					}
				}
			}
		}
		// 开始时间
		if (!StringUtils.isEmpty(startDate)) {
			sql += " and ctime >= " + startDate;
		}
		// 结束时间
		if (!StringUtils.isEmpty(endDate)) {
			sql += " and ctime <= " + endDate;
		}
		List<BigDecimal> list = ifwDeviceAuzInfoDao.findByNativeSqlWithStr(sql, null);
		BigDecimal bd = list.get(0);
		return null != bd ? bd.intValue() + "" : "0";
	}

	public String getList(String[] pNames, Object[] pValues, String[] logics, String[] relations, int page, int rows)
			throws Exception {
		// 获取总数
		String rule = " order by model.ctime desc";
		JSONObject jo = new JSONObject();
		long total = iIfwAgentConsumeDAO.getPropertiesCount(pNames, pValues, logics, relations, rule);
		jo.put("total", total);
		// 获取列表
		int start = (page - 1) * rows;
		if (start < 0)
			start = 0;
		List<IfwAgentConsumeRecord> agentConsumeRecords = iIfwAgentConsumeDAO.findByPropertiesRule("*", pNames, pValues,
				logics, relations, rule, start, rows);
		JSONArray ja = new JSONArray();
		if (null != agentConsumeRecords && !agentConsumeRecords.isEmpty()) {
			for (IfwAgentConsumeRecord r : agentConsumeRecords) {
				JSONObject jobj = new JSONObject();
				jobj.put("agentConsumeIndex", r.getAgentConsumeIndex());
				IfwAgentRegInfo ifwAgentRegInfo = r.getIfwAgentRegInfo();
				if (null != ifwAgentRegInfo) {
					jobj.put("agentName", ifwAgentRegInfo.getAgentName());
				}
				IfwCardInfo ifwCardInfo = r.getIfwCardInfo();
				if (null != ifwCardInfo) {
					jobj.put("cardIndex", ifwCardInfo.getCardIndex());
					jobj.put("cardNum", ifwCardInfo.getCardNum());
					jobj.put("cardSta", ifwCardInfo.getCardSta());
				}
				IfwAgentDevInfo ifwAgentDevInfo = r.getIfwAgentDevInfo();
				if (null != ifwAgentDevInfo) {
					String sn = ifwAgentDevInfo.getSn();
					List<IfwSrouterMap> ifwSrouterMaps = iIfwSrouterMapDao.findByProperties(new String[] { "sn" },
							new Object[] { sn });
					if (null != ifwSrouterMaps && !ifwSrouterMaps.isEmpty()) {
						sn = ifwSrouterMaps.get(0).getFwsn();
					}
					jobj.put("sn", sn);
				}
				jobj.put("type", r.getType());
				jobj.put("point", r.getPoint());
				jobj.put("time", r.getTime());
				jobj.put("ctime", r.getCtime());
				jobj.put("result", r.getResult());
				jobj.put("host", r.getHost());
				jobj.put("ac", r.getAc());
				ja.add(jobj);
			}
		}
		jo.put("rows", ja);
		return jo.toString();
	}
}
